package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicalException;
import cn.wolfcode.wolf2w.query.QueryObject;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQueryObject;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.PagingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;


    @Override
    public void save(Travel travel) {
        travel.setId(null);   //设为空值,防止数据库不会自动创建id
        repository.save(travel);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);

    }

    @Override
    public void update(Travel travel) {
        repository.save(travel);
    }

    @Override
    public Travel get(String id) {
        if (!StringUtils.hasLength(id)){
            return null;
        }
        Optional<Travel> optional = repository.findById(id);

        //判断是否存在
        if (optional.isPresent()){
            //获取对象
            Travel travel = optional.get();
            //设置作者
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            //设置目的地
            travel.setDest(destinationService.get(travel.getDestId()));
            return travel;
        }

        return null;
    }

    @Override
    public List<Travel> list() {
        return repository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQueryObject qo) {


        //查询封装类
        Query query = new Query();


        //发布的才展示
        query.addCriteria(Criteria.where("isPublic").is(Travel.ISPUBLIC_YES));

        //旅游天数
        if (qo.getDayType() > -1){
            TravelCondition travelCondition = TravelCondition.DAY_MAP.get(qo.getDayType());
            query.addCriteria(Criteria.where("day")
                    .gte(travelCondition.getMin()).lte(travelCondition.getMax()));
        }

        //旅游人均消费
        if (qo.getPerExpendType() > -1){
            TravelCondition travelCondition = TravelCondition.PEREXPEND_MAP.get(qo.getPerExpendType());
            query.addCriteria(Criteria.where("perExpend")
                    .gte(travelCondition.getMin()).lte(travelCondition.getMax()));
        }

        //目的地
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }

        //状态判断
        if (qo.getState() ==  -1){
            query.addCriteria(Criteria.where("state").is(Travel.STATE_REJECT));
        }else if (qo.getState() == 1){
            query.addCriteria(Criteria.where("state").is(Travel.STATE_WAITING));
        }
        //查询分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                Sort.Direction.DESC, "_id");

        //最新最热的条件
        if (qo.getOrderType() == 1){
            pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                    Sort.Direction.DESC, "releaseTime");

        }else if (qo.getOrderType() == 2){
            pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                    Sort.Direction.DESC, "viewnum");
        }



        //调用工具方法,返回分页数据
        Page<Travel> page = PagingUtil.query(query, template, Travel.class, pageable);
        for (Travel travel : page) {
            //获取作者
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            //将作者添加到对象中
            travel.setAuthor(userInfo);
        }

        return page;

    }

    @Override
    public String saveOrUpdate(Travel travel) {
        System.err.println(travel.getId());

        //添加缺少的字段
        //目的地名字
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDestName(destination.getName());
        //最后更新时间
        travel.setLastUpdateTime(new Date());
        //判断是否有id
        if (StringUtils.hasLength(travel.getId())){
            //创建时间
            travel.setCreateTime(travel.getCreateTime());
            //各种评论点赞
            travel.setViewnum(travel.getViewnum());
            travel.setReplynum(travel.getReplynum());
            travel.setFavornum(travel.getFavornum());
            travel.setSharenum(travel.getSharenum());
            travel.setThumbsupnum(travel.getThumbsupnum());
            //这里是全量更新
            this.update(travel);
        }else {
            //创建时间
            travel.setCreateTime(new Date());

            this.save(travel);
        }
        return travel.getId();
    }

    @Override
    public void audit(String id, int state) {
        if (!StringUtils.hasLength(id)){
            throw new LogicalException("参数异常");
        }
      //1.游记对象
        Travel travel = this.get(id);

        //2.判断该对象状态是否能审核
        if (travel.getState() == Travel.STATE_NORMAL){
            throw new LogicalException("参数异常");
        }

      //3.审核成功后
        if (Travel.STATE_RELEASE == state){
            //设置状态
            travel.setState(state);
            //设置发布时间
            travel.setReleaseTime(new Date());
            //设置最后更新时间
            travel.setLastUpdateTime(new Date());
        }else if(Travel.STATE_REJECT == state) {
            //4.审核拒绝后
            //拒绝后设置状态为拒绝,
            travel.setState(Travel.STATE_REJECT);
            //设置最后更新时间
            travel.setLastUpdateTime(new Date());
        }else {
            //下架后设置状态为待发布,
            travel.setState(Travel.STATE_WAITING);
            //设置最后更新时间
            travel.setLastUpdateTime(new Date());
        }

      //更新
        this.update(travel);

    }

    @Override
    public List<Travel> queryTravelsTop3(String destId) {
        //分页
        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC,"viewnum");
        //list
        List<Travel> travels = repository.findByDestId(destId,pageable);

        return travels;
    }


}
